//=========================================================================
// Copyright (C) 2024 The C++ Component Model(COMO) Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================

#ifndef TIME_WHEEL_SCHEDULER_H_
#define TIME_WHEEL_SCHEDULER_H_

#include <mutex>
#include <vector>
#include <thread>
#include <unordered_set>

#include "time_wheel.h"

namespace como {

class TimeWheelScheduler {
public:
    explicit TimeWheelScheduler(uint32_t timer_step_ms = 50);

    // Return timer id. Return 0 if the timer creation fails.
    uint32_t CreateTimerAt(int64_t when_ms, const TimerTask& task);
    uint32_t CreateTimerAfter(int64_t delay_ms, const TimerTask& task);
    uint32_t CreateTimerEvery(int64_t interval_ms, const TimerTask& task);

    void CancelTimer(uint32_t timer_id);

    bool Start();
    void Stop();

    void AppendTimeWheel(uint32_t scales, uint32_t scale_unit_ms, const std::string& name = "");

private:
    void Run();

    TimeWheelPtr GetGreatestTimeWheel();
    TimeWheelPtr GetLeastTimeWheel();

private:
    std::mutex mutex_;
    std::thread thread_;

    bool stop_;

    std::unordered_set<uint32_t> cancel_timer_ids_;

    uint32_t timer_step_ms_;
    std::vector<TimeWheelPtr> time_wheels_;
};

} // namespace como

#endif  // TIME_WHEEL_SCHEDULER_H_
